<?php

namespace App\Http\Model;

use App\Http\Services\GoodsLevelServices;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;


class Mall extends Base
{
    public $table = 'mall_goods';
    protected $skuTable = 'mall_goods_sku';
    protected $userGoodsTable = 'mall_user_goods';
    protected $shoplogTable = 'mall_shoplog';
    protected $tableLabel = 'mall_goods_label';
    protected $tableMallUnionGoods = 'mall_union_goods';
    protected $tableMallGoodsUpgradeConfig = 'mall_goods_upgrade_config';

    public $timestamps = false;
    private $redis_cache_mall_attires_key = 'CACHE:MALL:USER:ATTIRES'; //CACHE:MALL:USER:ATTIRES
    private $redis_cache_mall_animate_resources = "CACHE:MALL:ANIMATE:RESOURCES";
    protected $redis_register_mall = 'CACHE:MALL:REGISTER';
    protected $CacheMallGoodsConfig = 'CACHE:MALL:GOODS:UPGRADE:CONFIG:%s';// 字符串 CACHE:MALL:GOODS:UPGRADE:CONFIG:GoodsId


    public function __construct(array $attributes = [])
    {
        parent::__construct($this->table, $attributes);
    }

    //商品列表
    public function getGoodsListData($goods_type, $page, $page_size, $is_cp = 0, $mall_goods_class=0)
    {
//        $fields = ['goods_id', 'goods_name', 'goods_type', 'small_img', 'big_img', 'animate_resource',  'is_new','animate_resource_small', 'give_data_id','is_new_mount','text_color'];
        $fields = ['mall_goods.*','mall_goods_label.name as label_name' ,'mall_goods_label.resource as label_resource'];

        $condition = ['goods_type' => $goods_type, 'is_show' => 1, 'extra_type' => 0];
        if ($mall_goods_class){
            $condition = array_merge($condition, ['mall_goods_class'=>$mall_goods_class]);
        }

        $operator = "=";
        if ($is_cp == 1) {
            $operator = "!=";
        }

        $document = DB::table($this->table )
            ->leftJoin($this->tableLabel ,$this->tableLabel.'.id','=',$this->table.'.label_id')
            ->where($condition)
            ->where("give_data_id", $operator, 0)
            ->orderBy('sort', 'asc')
            ->offset(($page) * $page_size)
            ->limit($page_size)
            ->get($fields);

        $result = self::objToArray($document);
        if (!empty($result)) {
            $imgSource = getPicDomain();

            $levelResule = (new GoodsLevelServices())->getGoosLevelList([]);
            $levelList = [];
            if ($levelResule && $levelList =$levelResule['data']){
                $levelList = array_column($levelList, NULL, 'level');
            }
            foreach ($result as $k => $v) {
                $result[$k]['sku_list'] = $this->getSkuDataByGoods($v['goods_id']);
                if (!empty($v['small_img'])) {
                    $result[$k]['small_img'] = $imgSource . $v['small_img'];
                }
                if (!empty($v['big_img'])) {
                    $result[$k]['big_img'] = $imgSource . $v['big_img'];
                }
                if (!empty($v['animate_resource'])) {
                    $result[$k]['animate_resource'] = $imgSource . $v['animate_resource'];
                }
                if (!empty($v['animate_resource_small'])) {
                    $result[$k]['animate_resource_small'] = $imgSource . $v['animate_resource_small'];
                }
                if (!empty($result[$k]['sku_list'])){
                    $result[$k]['price'] = $result[$k]['sku_list'][0]['price'];
                    $result[$k]['sku_id'] = $result[$k]['sku_list'][0]['sku_id'];
                    $result[$k]['time_limit'] = $result[$k]['sku_list'][0]['time_limit'];
                }
                if(!empty($v['label_resource'])){
                    $result[$k]['label_resource'] = $imgSource . $v['label_resource'];
                }
                if(!empty($v['url_start_time'])){
                    $result[$k]['url_start_time'] = strtotime($v['url_start_time']) >0 ? strtotime($v['url_start_time']) : 0;
                }
                if(!empty($v['url_end_time'])){
                    $result[$k]['url_end_time'] = strtotime($v['url_end_time']) >0 ? strtotime($v['url_end_time']) : 0;
                }
                if (!empty($v['animate_resource_big'])) {
                    $result[$k]['animate_resource_big'] = $imgSource . $v['animate_resource_big'];
                }

                //商品等级
                $levelInfo = [];
                if ($v['level']){
                    $levelInfo = $levelList[$v['level']]??[];
                }
                $result[$k]['level_info'] = $levelInfo;

                // 商品可升级配置
                $is_upgrade = $v['is_upgrade'];
                $upgradeConfig = [];
                if ($is_upgrade){
                    $upgradeConfig = $this->getGoodsUpConfig($v['goods_id']);
                    if ($upgradeConfig){
                        foreach ($upgradeConfig as $kUf => $valUf){
                            $upgradeConfig[$kUf]['img'] = build_image($valUf['img']);
                            $upgradeConfig[$kUf]['animate'] = build_image($valUf['animate']);
                        }
                    }
                }
                $result[$k]['upgrade_config'] = $upgradeConfig;

            }
        }
        return $result;
    }
    // 商城商品列表 普通商品+CP商品
    public function getGoodsList($goods_type, $page, $page_size, $mall_goods_class=0)
    {
        $fields = ['mall_goods.*','mall_goods_label.name as label_name' ,'mall_goods_label.resource as label_resource'];

        $condition = ['goods_type' => $goods_type, 'is_show' => 1, 'extra_type' => 0];
        if ($mall_goods_class){
            $condition = array_merge($condition, ['mall_goods_class'=>$mall_goods_class]);
        }

        $document = DB::table($this->table )
            ->leftJoin($this->tableLabel ,$this->tableLabel.'.id','=',$this->table.'.label_id')
            ->where($condition)
            ->orderBy('sort', 'asc')
            ->offset(($page) * $page_size)
            ->limit($page_size)
            ->get($fields);

        $result = self::objToArray($document);
        if (!empty($result)) {
            $imgSource = getPicDomain();

            $levelResule = (new GoodsLevelServices())->getGoosLevelList([]);
            $levelList = [];
            if ($levelResule && $levelList =$levelResule['data']){
                $levelList = array_column($levelList, NULL, 'level');
            }
            foreach ($result as $k => $v) {
                $result[$k]['sku_list'] = $this->getSkuDataByGoods($v['goods_id']);
                if (!empty($v['small_img'])) {
                    $result[$k]['small_img'] = $imgSource . $v['small_img'];
                }
                if (!empty($v['big_img'])) {
                    $result[$k]['big_img'] = $imgSource . $v['big_img'];
                }
                if (!empty($v['animate_resource'])) {
                    $result[$k]['animate_resource'] = $imgSource . $v['animate_resource'];
                }
                if (!empty($v['animate_resource_small'])) {
                    $result[$k]['animate_resource_small'] = $imgSource . $v['animate_resource_small'];
                }
                if (!empty($result[$k]['sku_list'])){
                    $result[$k]['price'] = $result[$k]['sku_list'][0]['price'];
                    $result[$k]['sku_id'] = $result[$k]['sku_list'][0]['sku_id'];
                    $result[$k]['time_limit'] = $result[$k]['sku_list'][0]['time_limit'];
                }
                if(!empty($v['label_resource'])){
                    $result[$k]['label_resource'] = $imgSource . $v['label_resource'];
                }
                if(!empty($v['url_start_time'])){
                    $result[$k]['url_start_time'] = strtotime($v['url_start_time']) >0 ? strtotime($v['url_start_time']) : 0;
                }
                if(!empty($v['url_end_time'])){
                    $result[$k]['url_end_time'] = strtotime($v['url_end_time']) >0 ? strtotime($v['url_end_time']) : 0;
                }
                if (!empty($v['animate_resource_big'])) {
                    $result[$k]['animate_resource_big'] = $imgSource . $v['animate_resource_big'];
                }

                //商品等级
                $levelInfo = [];
                if ($v['level']){
                    $levelInfo = $levelList[$v['level']]??[];
                }
                $result[$k]['level_info'] = $levelInfo;

                // 商品可升级配置
                $is_upgrade = $v['is_upgrade'];
                $upgradeConfig = [];
                if ($is_upgrade){
                    $upgradeConfig = $this->getGoodsUpConfig($v['goods_id']);
                    if ($upgradeConfig){
                        foreach ($upgradeConfig as $kUf => $valUf){
                            $upgradeConfig[$kUf]['img'] = build_image($valUf['img']);
                            $upgradeConfig[$kUf]['animate'] = build_image($valUf['animate']);
                        }
                    }
                }
                $result[$k]['upgrade_config'] = $upgradeConfig;

            }
        }
        return $result;
    }


    /**
     * 获取商品信息
     * @param $goods_id
     * @return mixed|null
     */
    public function get_goods($goods_id ,$is_show=1){
        $fields = ['goods_id', 'goods_name', 'goods_type', 'small_img', 'big_img', 'animate_resource', 'is_buy', 'is_new', 'is_new_mount', 'text_color', 'goods_desc', 'from_desc', 'from_url', 'url_start_time', 'url_end_time', 'animate_resource_small','animate_resource_md5', 'give_data_id','animate_resource_big','level','renew_card_num','is_upgrade','cool_val','debris_num'];
//        if($is_show ==1){
//            $condition = ['goods_id' => $goods_id, 'is_show' => $is_show];
//        }else{
//            $condition = ['goods_id' => $goods_id];
//        }
        $condition = ['goods_id' => $goods_id, 'is_show' => 1];
        $document = DB::table($this->table )
            ->where($condition)
            ->first($fields);
        if (empty($document)){
            return null;
        }
        $result = self::objToArray($document);
        if (!empty($result)) {
            $result['sku_list'] = $this->getSkuDataByGoods($result['goods_id']);
            $imgSource = getPicDomain();
            if (!empty($result['small_img'])) {
                $result['small_img'] = $imgSource . $result['small_img'];
            }
            if (!empty($result['big_img'])) {
                $result['big_img'] = $imgSource . $result['big_img'];
            }
            if (!empty($result['animate_resource'])) {
                $result['animate_resource'] = $imgSource . $result['animate_resource'];
            }
            if (!empty($result['animate_resource_small'])) {
                $result['animate_resource_small'] = $imgSource . $result['animate_resource_small'];
            }
            if (!empty($result['animate_resource_big'])) {
                $result['animate_resource_big'] = $imgSource . $result['animate_resource_big'];
            }
            if(!empty($result['url_start_time'])){
                $result['url_start_time'] = strtotime($result['url_start_time']) >0 ? strtotime($result['url_start_time']) : 0;
            }
            if(!empty($result['url_end_time'])){
                $result['url_end_time'] = strtotime($result['url_end_time']) >0 ? strtotime($result['url_end_time']) : 0;
            }

        }
        return $result;
    }

    /**
     * 根据id读取商品数据
     * @return mixed
     */
    public function getGoodsByIds($goodsIds){
        $fields = ['goods_id','goods_name','goods_type','small_img','big_img','animate_resource','is_new_mount', 'text_color', 'goods_desc', 'from_desc', 'from_url', 'url_start_time', 'url_end_time', 'level','is_upgrade','cool_val','renew_card_num','debris_num'];
        $res = DB::table($this->table)
            ->whereIn('goods_id',$goodsIds)
            ->get($fields);
        $res = $this->objToArray($res);
        return $res;
    }

    //规格信息
    public function getSkuDataByGoods($goods_id)
    {
        $fields = ['sku_id', 'time_limit', 'price'];
        $document = DB::table($this->skuTable)
            ->where(['goods_id' => $goods_id])
            ->orderBy('price', 'asc')
            ->get($fields);
        return self::objToArray($document);
    }

    //获取商品及sku
    public function getSkuData($goods_id, $sku_id)
    {
        $fields = ['ku.sku_id', 'ku.time_limit', 'ku.price', 'go.goods_name', 'go.goods_type'];
        $document = DB::table($this->skuTable . ' as ku')
            ->join($this->table . ' as go', 'ku.goods_id', '=', 'go.goods_id')
            ->where(['ku.goods_id' => $goods_id, 'ku.sku_id' => $sku_id])
            ->first($fields);
        return self::objToArray($document);
    }

    public function getSkuInfo($sku_id)
    {
        $skuInfo = DB::table($this->skuTable)
            ->where('sku_id', $sku_id)
            ->first(['goods_id','time_limit']);

        return self::objToArray($skuInfo);
    }

    public function getSkuBySkuId($sku_id)
    {
        $skuInfo = DB::table($this->skuTable)
            ->where('sku_id', $sku_id)
            ->first();

        return self::objToArray($skuInfo);
    }

    public function getMallGoodByGoodsId($goods_id)
    {
        $skuInfo = DB::table($this->table)
            ->where('goods_id', $goods_id)
            ->first();

        return self::objToArray($skuInfo);
    }

    //获取收到的且未过期礼物
    /*
     * $goods_status valid有效 expire过期失效 all全
     */
    public function getUserGoodsList($user_id, $goods_type, $page = null, $page_size = null, $goods_status='valid')
    {
        $time = time();
        $fields = [
            'ug.id', 'ug.goods_id', 'ug.goods_type', 'ug.end_timestamp', 'ug.is_use','ug.level as use_upgrade_level',
            'go.goods_name', 'go.small_img', 'go.big_img', 'go.animate_resource','go.animate_resource_small','go.is_new_mount','go.text_color','go.goods_desc','go.is_buy','go.is_show','go.from_url','go.from_desc', 'go.url_start_time','go.url_end_time','go.level','go.cool_val','go.debris_num','go.is_upgrade','go.renew_card_num','go.animate_resource_big',
            'ml.name as label_name' ,'ml.resource as label_resource'
        ];
        $condition = ['ug.user_id' => $user_id, 'ug.goods_type' => $goods_type];
//        $document = DB::table($this->userGoodsTable . ' as ug')
//            ->leftJoin($this->table . ' as go', 'ug.goods_id', '=', 'go.goods_id')
//            ->where($condition)
//            ->where("ug.end_timestamp", '>=', $time)
//            ->orderBy('ug.create_timestamp', 'desc')
//            ->offset(($page) * $page_size)
//            ->limit($page_size)
//            ->get($fields);

        $query = DB::table($this->userGoodsTable . ' as ug')
            ->leftJoin($this->table . ' as go', 'ug.goods_id', '=', 'go.goods_id')
            ->leftJoin($this->tableLabel . ' as ml','ml.id','=','go.label_id')
            ->where($condition);
        if ($goods_status=='valid'){
            $query = $query -> where("ug.end_timestamp", '>=', $time);
        }elseif ($goods_status=='expire'){
            $query = $query -> where("ug.end_timestamp", '<', $time);
        }
        $query = $query -> orderBy('go.level', 'desc');
        $query = $query -> orderBy('ug.create_timestamp', 'desc');
        $query = $query -> orderBy('ug.id', 'asc');

        if($page == null || $page_size == null){
        } else {
            $query = $query->offset(($page) * $page_size);
        }
        if( !empty($page_size) ){
            $query = $query->limit($page_size);
        }

        $document = $query->get($fields);

        $result = self::objToArray($document);

        if (!empty($result)) {
            $imgSource = getPicDomain();

            $levelResule = (new GoodsLevelServices())->getGoosLevelList([]);
            $levelList = [];
            if ($levelResule && $levelList =$levelResule['data']){
                $levelList = array_column($levelList, NULL, 'level');
            }

            foreach ($result as $k => $v) {
                if (!empty($v['small_img'])) {
                    $result[$k]['small_img'] = $imgSource . $v['small_img'];
                }
                if (!empty($v['big_img'])) {
                    $result[$k]['big_img'] = $imgSource . $v['big_img'];
                }
                if (!empty($v['animate_resource'])) {
                    $result[$k]['animate_resource'] = $imgSource . $v['animate_resource'];
                }
                if (!empty($v['animate_resource_small'])) {
                    $result[$k]['animate_resource_small'] = $imgSource . $v['animate_resource_small'];
                }
                if(!empty($v['label_resource'])){
                    $result[$k]['label_resource'] = $imgSource . $v['label_resource'];
                }
                if(!empty($v['url_start_time'])){
                    $result[$k]['url_start_time'] = strtotime($v['url_start_time']) >0 ? strtotime($v['url_start_time']) : 0;
                }
                if(!empty($v['url_end_time'])){
                    $result[$k]['url_end_time'] = strtotime($v['url_end_time']) >0 ? strtotime($v['url_end_time']) : 0;
                }
                if (!empty($v['animate_resource_big'])) {
                    $result[$k]['animate_resource_big'] = $imgSource . $v['animate_resource_big'];
                }
                //商品等级
                $levelInfo = [];
                if ($v['level']){
                    $levelInfo = $levelList[$v['level']]??[];
                }
                $result[$k]['level_info'] = $levelInfo;

                // 商品可升级配置
                $is_upgrade = $v['is_upgrade'];
                $upgradeConfig = [];
                if ($is_upgrade){
                    $upgradeConfig = $this->getGoodsUpConfig($v['goods_id']);
                    if ($upgradeConfig){
                        foreach ($upgradeConfig as $kUc => $valUc){
                            $upgradeConfig[$kUc]['img'] = build_image($valUc['img']);
                            $upgradeConfig[$kUc]['animate'] = build_image($valUc['animate']);
                        }
                    }
                }
                $result[$k]['upgrade_config'] = $upgradeConfig;

            }
        }
        return $result;
    }

    //购买&赠送礼物
    public function shoppingAct($user_id, $to_user_id, $goods_id, $goods_name, $goods_type, $sku_id, $time_limit, $price, $end_time, $create_time, $act_type, $source_type = 0)
    {
        $logData = ['user_id' => $user_id, 'goods_id' => $goods_id, 'goods_name' => $goods_name, 'sku_id' => $sku_id, 'time_limit' => $time_limit, 'create_timestamp' => $create_time, 'price' => $price];
        $goodsData = ['goods_id' => $goods_id, 'goods_name' => $goods_name, 'goods_type' => $goods_type, 'end_timestamp' => $create_time + $end_time, 'create_timestamp' => $create_time, 'update_timestamp'=>$create_time];
        $ck_where = ['user_id' => $user_id, 'goods_id' => $goods_id];
        if ($act_type == 1) {
            $goodsData['user_id'] = $user_id;
            $goodsData['source_type'] = 1;
            $ck_where['user_id'] = $user_id;
        } else {
            $goodsData['user_id'] = $to_user_id;
            $goodsData['source_type'] = 2;
            $logData['to_user_id'] = $to_user_id;
            $ck_where['user_id'] = $to_user_id;
        }
        if(0 != $source_type) $goodsData['source_type'] = $source_type;
        $goods = DB::table($this->userGoodsTable)->where($ck_where)->first();
        $ug_id = null;
        if (empty($goods)){
            $ug_id = DB::table($this->userGoodsTable)->insertGetId($goodsData);//商品
        }else{
            DB::table($this->userGoodsTable)->where($ck_where)->increment('end_timestamp',$end_time,['update_timestamp'=>$create_time]);
            $goods =  self::objToArray($goods);
            if ( $goods['end_timestamp']<time() ){
                // 装扮过期后 初始化装扮数据 && ($goods['is_use']==1 || $goods['level']!=0)
                DB::table($this->userGoodsTable)->where($ck_where)->update(['is_use'=>0, 'level'=>0]);
            }
            if ($goods['end_timestamp'] < $create_time){
                DB::table($this->userGoodsTable)->where($ck_where)->update(['end_timestamp'=>$create_time + $end_time, 'update_timestamp'=>$create_time]);
            }
            $ug_id = $goods['id'];
        }

        if ($act_type != 3) {
            DB::table($this->shoplogTable)->insert($logData);//日志
        }

        $this->del_cache_mall_attires($goodsData['user_id']); //清理缓存

        $ret_data = [
            'user_id' => $user_id, 'goods_id' => $goods_id, 'goods_name' => $goods_name, 'sku_id' => $sku_id, 'id' => $ug_id, 'goods_type' => $goods_type
        ];
        return $ret_data;
    }

    //系统赠送指定用户礼物根据skuID
    public function giveUserGoodBySkuId($to_user_id, $skuId, $time_limit, $end_time)
    {
        $ressult = [];
        do {
            $goodsSku = $this->getSkuBySkuId($skuId);
            if(empty($goodsSku)) {
                break;
            }
            $goodInfo = $this->getMallGoodByGoodsId($goodsSku['goods_id']);
            if(empty($goodInfo)) {
                break;
            }

            $ressult = $this->shoppingAct(
                11,
                $to_user_id,
                $goodsSku['goods_id'],
                $goodInfo['goods_name'],
                $goodInfo['goods_type'],
                $goodsSku['sku_id'],
                $time_limit,
                0,
                $end_time,
                time(),
                2
            );
        } while (false);

        return $ressult;
    }

    //获取特定装扮是否有效
    public function getGoodsAttrie($userId, $id)
    {
        $time = time();
        $document = DB::table($this->userGoodsTable)
            ->where(['user_id' => $userId, 'id' => $id])
            ->where("end_timestamp", '>=', $time)
            ->first();
        return self::objToArray($document);
    }
    //获取特定装扮是否有效
    public function getUserGoodsInfo($userId, $goodsId)
    {
        $time = time();
        $document = DB::table($this->userGoodsTable)
            ->where('user_id', $userId)
            ->where('goods_id', $goodsId)
            ->where("end_timestamp", '>=', $time)
            ->first(['user_id','goods_id','end_timestamp']);

        return self::objToArray($document);
    }


    /**
     *  设置装扮
     * @param $userId
     * @param $id
     * @param $goodsType
     * @param int $level  -佩戴升级的等级mall_goods_upgrade_config.level
     * @return int
     */
    public function setGoodsAttrie($userId, $id, $goodsType, $upgrade_level=0)
    {
        $upgrade_level = intval($upgrade_level);
        $ret = DB::table($this->userGoodsTable)
            ->where(['id' => $id,'goods_type' => $goodsType])
            ->update(['is_use' => 1, 'level' => $upgrade_level, 'update_timestamp'=>time()]);
        DB::table($this->userGoodsTable)
            ->where(['user_id' => $userId, 'goods_type' => $goodsType])
            ->where('id', '!=', $id)
            ->update(['is_use' => 0, 'level' => 0]);

        $this->del_cache_mall_attires($userId); //清理缓存
        return $ret;
    }

    /**
     * 取消装扮
     * @param $userId
     * @param $goodsType
     * @return int
     */
    public function cancelGoodsAttrie($userId, $goodsType)
    {
        $ret = DB::table($this->userGoodsTable)
            ->where(['user_id' => $userId,'goods_type' => $goodsType])
            ->update(['is_use' => 0, 'level' => 0]);
        $this->del_cache_mall_attires($userId); //清理缓存
        return $ret;
    }
    /**
     * 作废装扮
     * @param $userId
     * @param $goodsIdArr 数组
     * @return int
     */
    public function onVoidGoodsAttrie($userId, $goodsIdArr)
    {
        $this->del_cache_mall_attires($userId); //清理缓存
        $ret = DB::table($this->userGoodsTable)
            ->where('user_id', $userId)
            ->whereIn('goods_id', $goodsIdArr)
            ->update(['end_timestamp'=> 0]);// 作废 失效处理
        return $ret;
    }


    //获取已设置装扮
    public function getGoodsAttire($userId)
    {
        $cache = $this->get_cache_mall_attires($userId);

        if ($cache != null){
            $new_cache = array_filter($cache,function ($value){
                return $value['end_timestamp'] >= $_SERVER['REQUEST_TIME'];
            });

            if(count($new_cache) < count($cache)){
                $this->set_cache_mall_attires($userId, $new_cache);
            }
            return $new_cache;
        }
        $time = time();
        $fields = ['ug.goods_id', 'ug.goods_type', 'ug.goods_name', 'ug.level as upgrade_level', 'go.small_img', 'go.big_img', 'go.animate_resource','ug.end_timestamp', 'go.animate_resource_md5','go.animate_resource_small', 'go.vapc_json_url', 'go.is_new_mount','go.text_color','go.animate_resource_big', 'go.is_upgrade'];
        $condition = ['ug.user_id' => $userId, 'ug.is_use' => 1];
        $document = DB::table($this->userGoodsTable . ' as ug')
            ->leftJoin($this->table . ' as go', 'ug.goods_id', '=', 'go.goods_id')
            ->where($condition)
            ->where("ug.end_timestamp", '>=', $time)
            ->orderBy('ug.goods_type', 'asc')
            ->get($fields);

        $result = self::objToArray($document);

        if (!empty($result)) {
            $imgSource = getPicDomain();
            foreach ($result as $k => $v) {

                // 等级资源
                // 商品可升级配置
                $is_upgrade = $v['is_upgrade'];
                $upgrade_level = $v['upgrade_level'];
                if ($upgrade_level>=0 && $is_upgrade){
                    $upgradeConfig = $this->getGoodsUpConfig($v['goods_id']);
                    if ($upgradeConfig){
                        $upgradeConfig = array_column($upgradeConfig, NULL, 'level');
                        $levelInfo = $upgradeConfig[$upgrade_level] ?? NULL;
                        if ($levelInfo){
                            if ($levelInfo['img']){
                                $v['small_img'] = $levelInfo['img'];
                                $v['big_img'] = $levelInfo['img'];
                            }
                            if ($levelInfo['animate']){
                                $v['animate_resource'] = $levelInfo['animate'];
                                $v['animate_resource_small'] = $levelInfo['animate'];
                                $v['animate_resource_big'] = $levelInfo['animate'];
                                $v['animate_resource_md5'] = $levelInfo['animate_md5'];
                            }
                        }
                    }
                }

                if (!empty($v['small_img'])) {
                    $result[$k]['small_img'] = $imgSource . $v['small_img'];
                }
                if (!empty($v['big_img'])) {
                    $result[$k]['big_img'] = $imgSource . $v['big_img'];
                }
                if (!empty($v['animate_resource'])) {
                    $result[$k]['animate_resource'] = $imgSource . $v['animate_resource'];
                }
                if (!empty($v['vapc_json_url'])) {
                    $result[$k]['vapc_json_url'] = $imgSource . $v['vapc_json_url'];
                }
                if (!empty($v['animate_resource_small'])) {
                    $result[$k]['animate_resource_small'] = $imgSource . $v['animate_resource_small'];
                }
                if (!empty($v['animate_resource_big'])) {
                    $result[$k]['animate_resource_big'] = $imgSource . $v['animate_resource_big'];
                }
            }
        }
        $this->set_cache_mall_attires($userId, $result);
        return $result;

    }

    //获取用户可升级装扮
    public function getUserUpgradeGoodsAttire($userId, $goodsId)
    {
        $time = time();
        $fields = ['ug.goods_id', 'ug.goods_type', 'go.is_upgrade'];
        $condition = ['ug.user_id' => $userId, 'go.goods_id'=>$goodsId, 'ug.is_use' => 1, 'go.is_upgrade'=> 1];
        $document = DB::table($this->userGoodsTable . ' as ug')
            ->leftJoin($this->table . ' as go', 'ug.goods_id', '=', 'go.goods_id')
            ->where($condition)
            ->where("ug.end_timestamp", '>=', $time)
            ->orderBy('ug.goods_type', 'asc')
            ->get($fields);

        $result = self::objToArray($document);

        return $result;

    }



    public function get_goods_attire_ids($list_user_id){
        $time = time();
        $fields = ['ug.goods_id', 'ug.goods_type', 'ug.goods_name', 'go.small_img', 'go.big_img', 'go.animate_resource', 'ug.user_id','ug.end_timestamp','go.animate_resource_small','go.animate_resource_big'];
        $document = DB::table($this->userGoodsTable . ' as ug')
            ->leftJoin($this->table . ' as go', 'ug.goods_id', '=', 'go.goods_id')
            ->where("ug.end_timestamp", '>=', $time)
            ->where('ug.is_use', '=', 1)
            ->whereIn("ug.user_id", $list_user_id)
            ->orderBy('ug.goods_type', 'asc')
            ->get($fields);

        $result = self::objToArray($document);

        if (!empty($result)) {
            $imgSource = getPicDomain();
            foreach ($result as $k => $v) {
                if (!empty($v['small_img'])) {
                    $result[$k]['small_img'] = $imgSource . $v['small_img'];
                }
                if (!empty($v['big_img'])) {
                    $result[$k]['big_img'] = $imgSource . $v['big_img'];
                }
                if (!empty($v['animate_resource'])) {
                    $result[$k]['animate_resource'] = $imgSource . $v['animate_resource'];
                }
                if (!empty($v['animate_resource_small'])) {
                    $result[$k]['animate_resource_small'] = $imgSource . $v['animate_resource_small'];
                }
                if (!empty($v['animate_resource_big'])) {
                    $result[$k]['animate_resource_big'] = $imgSource . $v['animate_resource_big'];
                }
            }
        }
        $map_attire = [];
        for ($i = 0; $i < count($result); $i++){
            if (!array_key_exists(intval($result[$i]['user_id']), $map_attire)){
                $map_attire[intval($result[$i]['user_id'])] = [];
            }
            array_push( $map_attire[intval($result[$i]['user_id'])], $result[$i]);
        }
        return $map_attire;
    }


    /**
     * 获取预加载资源列表
     * @return array
     */
    public function get_animate_resources(){
        $data = Redis::GET($this->redis_cache_mall_animate_resources);
        if (!empty($data)){
            return json_decode($data, true);
        }
        $res = DB::table("mall_goods")
            ->where('goods_type', '=', 2)
            ->get(['goods_id', 'animate_resource', 'animate_resource_md5']);
        $result = self::objToArray($res);
        for ($i = 0; $i < count($result); $i++){
            $result[$i]['animate_resource'] = getPicDomain() .  $result[$i]['animate_resource'];
        }
        Redis::SET($this->redis_cache_mall_animate_resources, json_encode($result));
        Redis::EXPIRE($this->redis_cache_mall_animate_resources, 3600);
        return $result;
    }


    /**
     * 设置用户装扮缓存
     * @param $user_id
     * @param $attires
     * @return bool
     */
    private function set_cache_mall_attires($user_id, $attires){
        $key = $this->redis_cache_mall_attires_key;
        Redis::HSET($key, $user_id, json_encode(array_values($attires)));
        return true;
    }


    /**
     * 获取用户装扮缓存
     * @param $user_id
     * @return mixed|null
     */
    private function get_cache_mall_attires($user_id){
        $key = $this->redis_cache_mall_attires_key;
        $ret = Redis::HGET($key, $user_id);
        if ($ret == null){
            return null;
        }
        return json_decode($ret, true);
    }


    /**
     * 删除用户装扮缓存
     * @param $user_id
     * @return bool
     */
    public function del_cache_mall_attires($user_id){
        $key = $this->redis_cache_mall_attires_key;
        Redis::HDEL($key, $user_id);
        return true;
    }

    /**根据商品ids 获取商品详情
     * @param $goods_id
     * @return mixed
     */
    public function getGoodsByGoodIds($goods_id){
        $fields = ['goods_id', 'goods_name', 'goods_type', 'small_img', 'big_img', 'animate_resource',  'is_new','animate_resource_small','give_data_id'];
        $document = DB::table($this->table )
            ->whereIn('goods_id' ,$goods_id)
            ->where('is_show',1)
            ->get($fields);
        return $this->objToArray($document);
    }
    /**根据商品ids 获取全部商品详情
     * @param $goods_id
     * @return mixed
     */
    public function getGoodsAllByGoodIds($goods_id){
        $fields = ['goods_id', 'goods_name', 'goods_type', 'small_img', 'big_img', 'animate_resource',  'is_new','animate_resource_small','give_data_id'];
        $document = DB::table($this->table )
            ->whereIn('goods_id' ,$goods_id)
            ->get($fields);
        return $this->objToArray($document);
    }

    /**
     * 创建公会商品
     */
    public function createMallUnionGoods(array $data = []) {
        return DB::table($this->tableMallUnionGoods)->insertGetId($data);
    }

    /**
     * 更新公会商品
     */
    public function updateMallUnionGoods(int $id, array $data = []) {
        return DB::table($this->tableMallUnionGoods)->where('m_u_g_id', $id)->update($data);
    }

    public function getMallUnionGoodsByCondition(array $condition = [], array $fields = ['*']) {
        return DB::table($this->tableMallUnionGoods)->where($condition)->get($fields)->toArray();
    }

    public function checkMallUnionGoods($unionId,  $notMugid) {
        return DB::table($this->tableMallUnionGoods)
            ->where('union_id', $unionId)
            ->whereNotIn('m_u_g_id', [$notMugid])
            ->exists();
    }


    public function getMallUnionGoodsId(int $union_id)
    {
        return DB::table($this->tableMallUnionGoods)
            ->where('union_id', $union_id)
            ->where('status', 0)
            ->value('good_id');
    }

    /**
     * 根据指定条件更新用户商品
     */
    public function updateMallUserGoodsByCondition(array $condition = [], array $data = []) {
        return DB::table($this->userGoodsTable)->where($condition)->update($data);
    }

    public function deleteMallUnionGoods(int $unionId) {
        return DB::table($this->tableMallUnionGoods)->where('union_id', $unionId)->delete();
    }



    /***************商品升级配置信息*-tableMallGoodsUpgradeConfig***************/

    public function delGoodsUpConfigByGid(int $goods_id) {
        $CacheKey = $this->CacheMallGoodsConfig;
        $CacheKey = sprintf($CacheKey, $goods_id);
        Redis::del($CacheKey);
        return DB::table($this->tableMallGoodsUpgradeConfig)->where('goods_id', $goods_id)->delete();
    }
    public function createGoodsUpConfig(array $data = []) {
        return DB::table($this->tableMallGoodsUpgradeConfig)->insert($data);
    }

    /**
     * 获取商品可升级配置
     * @param $goods_id
     * @return mixed
     */
    public function getGoodsUpConfig($goods_id) {
        $CacheKey = $this->CacheMallGoodsConfig;
        $CacheKey = sprintf($CacheKey, $goods_id);
        $Cache = Redis::get($CacheKey);
        $list = json_decode($Cache, true);
        if (empty($list)){
            $list = DB::table($this->tableMallGoodsUpgradeConfig)->where('goods_id', $goods_id)->get();
            $list = $this -> objToArray($list);
            if ($list){
                Redis::set($CacheKey, json_encode($list), 'EX', 7200);
            }
        }
        return $list;
    }
    /***************商品升级配置信息*-tableMallGoodsUpgradeConfig***************/



    //获取用户已装备指定类型装备
    public function getUserUseGoods($userId, $goodsType)
    {
        $document = DB::table($this->userGoodsTable)
            ->where('user_id', $userId)
            ->where('user_id', $goodsType)
            ->where('is_use', 1)
            ->first();
        return self::objToArray($document);
    }

}
